package com.example.huanhang.changzhouapp.activity;

import android.app.DownloadManager;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.huanhang.changzhouapp.R;
import com.tencent.smtt.sdk.TbsReaderView;

import java.io.File;
import java.text.DecimalFormat;

/**
 * @desc android5.0以下系统使用腾讯TBS阅览pdf
 * @author  lei
 * @date  2018/10/31 0031 -- 上午 8:54.
 * 个人博客站: http://www.bestlei.top
 */
public class ShowPdf2Activity extends AppCompatActivity implements TbsReaderView.ReaderCallback, View.OnClickListener {

    private TbsReaderView mTbsReaderView;
    private DownloadManager mDownloadManager;
    private long mRequestId;
    private DownloadObserver mDownloadObserver;
    private String mFileName;
    private String mUrl;
    private ImageView mImageView;
    private TextView mTvText;
    private LinearLayout mLl;
    private Button mDownloadBtn;
    private RelativeLayout mRlRoot;
    private ImageView mIvDelete;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_pdf2);
        initView();
        String pdfPath = getIntent().getStringExtra("pdfPath");
        mUrl = "http://211.159.176.93:8666/test/" + pdfPath;
        mTbsReaderView = new TbsReaderView(ShowPdf2Activity.this, this);
        mRlRoot.addView(mTbsReaderView, new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

        mFileName = parseName(mUrl);
        if (isLocalExist()) {
            mImageView.setImageResource(R.mipmap.cunzaiwenjian);
            mLl.setVisibility(View.VISIBLE);
            mTvText.setText("文件可直接打开");
            mDownloadBtn.setText("打开文件");
        }
    }



    private void displayFile() {
        Bundle bundle = new Bundle();
        bundle.putString("filePath", getLocalFile().getPath());
        bundle.putString("tempPath", Environment.getExternalStorageDirectory().getPath());
        boolean result = mTbsReaderView.preOpen(parseFormat(mFileName), false);
        if (result) {
            mTbsReaderView.openFile(bundle);
        }
    }

    private String parseFormat(String fileName) {
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    private String parseName(String url) {
        String fileName = null;
        try {
            fileName = url.substring(url.lastIndexOf("/") + 1);
        } finally {
            if (TextUtils.isEmpty(fileName)) {
                fileName = String.valueOf(System.currentTimeMillis());
            }
        }
        return fileName;
    }

    private boolean isLocalExist() {
        return getLocalFile().exists();
    }

    private File getLocalFile() {
        return new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), mFileName);
    }

    private void cancelDownload() {
        mDownloadManager.remove(mRequestId);
        mDownloadBtn.setText("开始下载");
        mIvDelete.setVisibility(View.GONE);
    }
    private void startDownload() {
        mIvDelete.setVisibility(View.VISIBLE);
        mDownloadObserver = new DownloadObserver(new Handler());
        getContentResolver().registerContentObserver(Uri.parse("content://downloads/my_downloads"), true, mDownloadObserver);
        mDownloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(mUrl));
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, mFileName);
        request.allowScanningByMediaScanner();
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
        mRequestId = mDownloadManager.enqueue(request);
    }

    private void queryDownloadStatus() {
        DownloadManager.Query query = new DownloadManager.Query().setFilterById(mRequestId);
        Cursor cursor = null;
        try {
            cursor = mDownloadManager.query(query);
            if (cursor != null && cursor.moveToFirst()) {
                //已经下载的字节数
                int currentBytes = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                //总需下载的字节数
                int totalBytes = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                //状态所在的列索引
                int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
                Log.i("downloadUpdate: ", currentBytes + " " + totalBytes + " " + status);
                mDownloadBtn.setText("正在下载：" + getDataSize(currentBytes) + "/" +getDataSize(totalBytes) );
                if (DownloadManager.STATUS_SUCCESSFUL == status && mDownloadBtn.getVisibility() == View.VISIBLE) {
                    mDownloadBtn.setVisibility(View.GONE);
                    mIvDelete.setVisibility(View.GONE);
                    mLl.setVisibility(View.GONE);
                    mDownloadBtn.performClick();
                }
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mTbsReaderView.onStop();
        if (mDownloadObserver != null) {
            getContentResolver().unregisterContentObserver(mDownloadObserver);
        }
    }

    @Override
    public void onCallBackAction(Integer integer, Object o, Object o1) {

    }

    private void initView() {
        mImageView = (ImageView) findViewById(R.id.imageView);
        mTvText = (TextView) findViewById(R.id.tv_text);
        mLl = (LinearLayout) findViewById(R.id.ll);
        mDownloadBtn = (Button) findViewById(R.id.btn_download);
        mRlRoot = (RelativeLayout) findViewById(R.id.rl_root);
        mIvDelete = (ImageView) findViewById(R.id.iv_delete);
        mDownloadBtn.setOnClickListener(this);
        mIvDelete.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_download:
                if (isLocalExist()) {
                    mDownloadBtn.setVisibility(View.GONE);
                    mIvDelete.setVisibility(View.GONE);
                    displayFile();
                } else {
                    startDownload();

                }
                break;
            case R.id.iv_delete:
                cancelDownload();
                break;
        }

    }


    private class DownloadObserver extends ContentObserver {

        private DownloadObserver(Handler handler) {
            super(handler);
        }

        @Override
        public void onChange(boolean selfChange, Uri uri) {
            Log.i("downloadUpdate: ", "onChange(boolean selfChange, Uri uri)");
            queryDownloadStatus();
        }
    }

    /**
     * 返回byte的数据大小对应的文本
     *
     * @param size
     * @return
     */
    public static String getDataSize(long size) {
        if (size < 0) {
            size = 0;
        }
        DecimalFormat formater = new DecimalFormat("####.00");
        if (size < 1024) {
            return size + "bytes";
        } else if (size < 1024 * 1024) {
            float kbsize = size / 1024f;
            return formater.format(kbsize) + "KB";
        } else if (size < 1024 * 1024 * 1024) {
            float mbsize = size / 1024f / 1024f;
            return formater.format(mbsize) + "MB";
        } else if (size < 1024 * 1024 * 1024 * 1024) {
            float gbsize = size / 1024f / 1024f / 1024f;
            return formater.format(gbsize) + "GB";
        } else {
            return String.valueOf(size);
        }

    }

}
